package com.greateffect.littlebud.lib.update;

import android.content.Context;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.github.lzyzsd.circleprogress.CircleProgress;
import com.greateffect.littlebud.lib.R;
import com.greateffect.littlebud.lib.dialog.CustomDialogHelper;
import com.greateffect.littlebud.lib.utilcode.ToastUtils;
import com.greateffect.littlebud.lib.utils.JLogUtil;
import com.pgyersdk.update.DownloadFileListener;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.pgyersdk.update.javabean.AppBean;

public class CheckUpdateUtil {
    private static CheckUpdateUtil sInstance;
    private boolean hasIgnoreThisTime = false;

    public static CheckUpdateUtil getInstance() {
        if (sInstance == null) {
            synchronized (CheckUpdateUtil.class) {
                if (sInstance == null) {
                    sInstance = new CheckUpdateUtil();
                }
            }
        }
        return sInstance;
    }


    private AlertDialog mConfirmDialog;

    /**
     * 显示升级提示框
     */
    private void showUpdateConfirmDialog(Context mContext, AppBean appBean) {
        if (mConfirmDialog == null) {
            String updateContent = appBean.getReleaseNote();
            if (TextUtils.isEmpty(updateContent))
                updateContent = "无版本更新说明。";
            else
                updateContent = "版本更新说明：\n" + updateContent;

            boolean isForce = updateContent.contains("[ForceUpdate]");
            if (isForce) {
                updateContent = updateContent.replace("[ForceUpdate]", "");
            }
            CustomDialogHelper.DialogParam dialogParam = new CustomDialogHelper.DialogParam(updateContent);
            String versionName = appBean.getVersionName();
            try {
                versionName = versionName.split("_")[0];
            } catch (Exception e) {
                e.printStackTrace();
            }
            dialogParam.setTitle("发现新版本：" + versionName);

            if (isForce) {
                dialogParam.setPositiveBtnText("立即更新");
                dialogParam.setNegativeBtnText("");
                dialogParam.setCenterContent(false);
                mConfirmDialog = CustomDialogHelper.showCustomConfirmDialogWithBtn(mContext, dialogParam, new CustomDialogHelper.NativeDialogCallback() {
                    @Override
                    public void onConfirm() {
                        // 下载APK
                        startDownloadByPgy(mContext, appBean.getDownloadURL());
                    }

                    @Override
                    public void onCancel() {
                        // do nothing
                    }
                });
                if (mConfirmDialog != null && CustomDialogHelper.canShowDialog(mContext)) {
                    mConfirmDialog.setCancelable(false);
                    mConfirmDialog.show();
                }
            } else {
                dialogParam.setPositiveBtnText("立即更新");
                dialogParam.setNegativeBtnText("暂不更新");
                dialogParam.setCenterContent(false);
                mConfirmDialog = CustomDialogHelper.showCustomConfirmDialogWithBtn(mContext, dialogParam, new CustomDialogHelper.NativeDialogCallback() {
                    @Override
                    public void onConfirm() {
                        // 下载APK
                        startDownloadByPgy(mContext, appBean.getDownloadURL());
                    }

                    @Override
                    public void onCancel() {
                        // do nothing
                        hasIgnoreThisTime = true;
                    }
                });
                if (mConfirmDialog != null && CustomDialogHelper.canShowDialog(mContext)) {
                    mConfirmDialog.setCancelable(true);
                    mConfirmDialog.show();
                }
            }
        } else {
            if (CustomDialogHelper.canShowDialog(mContext))
                mConfirmDialog.show();
        }
    }

    /**
     * 检测新版本
     */
    public void checkUpdateByPgy(Context context) {
        if (hasIgnoreThisTime) {
            JLogUtil.d("已经选择暂不更新。");
            return;
        }
        new PgyUpdateManager.Builder()
                .setForced(true)                // 设置是否强制提示更新,非自定义回调更新接口此方法有用
                .setUserCanRetry(true)          // 失败后是否提示重新下载，非自定义下载 apk 回调此方法有用
                .setDeleteHistroyApk(true)     // 检查更新前是否删除本地历史 Apk， 默认为true
                .setUpdateManagerListener(new UpdateManagerListener() {
                    @Override
                    public void onNoUpdateAvailable() {
                        // 没有更新是回调此方法
                        JLogUtil.d("当前已经是最新版本");
                    }

                    @Override
                    public void onUpdateAvailable(AppBean appBean) {
                        //有更新回调此方法
                        JLogUtil.d("pgyer", "there is new version can update new versionJson is " + JSON.toJSONString(appBean));
                        //调用以下方法，DownloadFileListener 才有效；
                        //如果完全使用自己的下载方法，不需要设置DownloadFileListener

                        showUpdateConfirmDialog(context, appBean);
                        // PgyUpdateManager.downLoadApk(appBean.getDownloadURL());
                    }

                    @Override
                    public void checkUpdateFailed(Exception e) {
                        // 更新检测失败回调
                        // 更新拒绝（应用被下架，过期，不在安装有效期，下载次数用尽）以及无网络情况会调用此接口
                        JLogUtil.e("pgyer", "check update failed ", e);
                    }
                })
                //注意 ：
                //下载方法调用 PgyUpdateManager.downLoadApk(appBean.getDownloadURL()); 此回调才有效
                //此方法是方便用户自己实现下载进度和状态的 UI 提供的回调
                //想要使用蒲公英的默认下载进度的UI则不设置此方法
                .setDownloadFileListener(new DownloadFileListener() {
                    @Override
                    public void downloadFailed() {
                        // 下载失败
                        JLogUtil.e("安装包下载失败。");
                        ToastUtils.showLong("安装包下载失败。");
                        CustomDialogHelper.dismissDialog(mDownloadDialog);
                    }

                    @Override
                    public void downloadSuccessful(Uri uri) {
                        CustomDialogHelper.dismissDialog(mDownloadDialog);
                        JLogUtil.e("安装包下载成功。");
                        // 使用蒲公英提供的安装方法提示用户 安装apk
                        PgyUpdateManager.installApk(uri);
                    }

                    @Override
                    public void onProgressUpdate(Integer... integers) {
                        if (mCircleProgress != null) {
                            mCircleProgress.setProgress(integers[0]);
                        }
                    }
                })
                .register();
    }

    private CircleProgress mCircleProgress;
    private AlertDialog mDownloadDialog;

    private void startDownloadByPgy(Context mContext, String url) {
        View dialog_view = LayoutInflater.from(mContext).inflate(R.layout.dialog_download_apk_progress, null, false);
        mDownloadDialog = CustomDialogHelper.showCustomDialog(mContext, dialog_view, false);
        mCircleProgress = dialog_view.findViewById(R.id.circle_progress);
        mCircleProgress.setProgress(0);

        PgyUpdateManager.downLoadApk(url);
    }

}
